package com.abel.bigwater.kmgw.impl

import com.abel.bigwater.dataserver.model.HgdaoDevice
import com.abel.bigwater.kmgw.dao.RtuDao
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.stereotype.Repository
import java.util.*

@Repository
class RtuDaoImpl : RtuDao {

    @Autowired
    var mongoTemplate: MongoTemplate? = null

    /**
     * 返回设备数量
     */
    override fun countRtu(_firmId: String): Long {
        return mongoTemplate!!.count(Query().addCriteria(Criteria.where(KEY_FIRM_ID).isEqualTo(_firmId)),
                COL_RTU_DEVICE)
    }

    /**
     * 返回指定水司的全部RTU。
     */
    override fun listRtu(_firmId: String): List<HgdaoDevice> {
        return mongoTemplate!!.find(Query().addCriteria(Criteria.where(KEY_FIRM_ID).isEqualTo(_firmId)),
                COL_RTU_DEVICE)
    }

    /**
     * 更新或者插入RTU设备档案。
     */
    override fun setRtu(rtu: HgdaoDevice): HgdaoDevice {
        assert(!rtu.firmId.isNullOrBlank())
        assert(!rtu.rtuId.isNullOrBlank())

        val filter = Query().addCriteria(Criteria.where(KEY_FIRM_ID).isEqualTo(rtu.firmId)
                .and(KEY_RTU_ID).`is`(rtu.rtuId))
        val old = mongoTemplate!!.find<HgdaoDevice>(filter, COL_RTU_DEVICE)

        if (old.size == 1) {
            rtu.also {
                it.createTime = old[0].createTime
                it.updateTime = Date()
            }
            mongoTemplate!!.findAndReplace(filter, rtu, COL_RTU_DEVICE)

            mongoTemplate!!.insert(old[0], COL_RTU_DEVICE_HIST)
        } else {
            rtu.createTime = Date()
            mongoTemplate!!.insert(rtu, COL_RTU_DEVICE)
        }

        return rtu
    }

    /**
     * 获取RTU设备档案
     */
    override fun fetchRtu(rtuId: String, _firmId: String): HgdaoDevice? {
        try {
            val filter = Query().addCriteria(Criteria.where(KEY_FIRM_ID).isEqualTo(_firmId)
                    .and(KEY_RTU_ID).`is`(rtuId))
            return mongoTemplate!!.find<HgdaoDevice>(filter, COL_RTU_DEVICE).firstOrNull()
        } catch (ex: Exception) {
            lgr.error("获取RTU配置失败: ${ex.message}", ex)
            return null
        }
    }

    /**
     * 移除RTU设备档案
     */
    override fun removeRtu(rtuId: String, _firmId: String): HgdaoDevice? {
        val filter = Query().addCriteria(Criteria.where(KEY_FIRM_ID).isEqualTo(_firmId)
                .and(KEY_RTU_ID).`is`(rtuId))
        val old = mongoTemplate!!.findAndRemove(filter, HgdaoDevice::class.java, COL_RTU_DEVICE)

        if (old != null) {
            old.updateTime = Date()
            mongoTemplate?.insert(old, COL_RTU_DEVICE_HIST)
        }

        return old
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(ConfigDaoImpl::class.java)

        const val COL_RTU_SETTING = "rtuSetting"

        const val HIST_COL_RTU_SETTING = "rtuSettingHist"

        const val COL_RTU_SETTING_RESP = "rtuSettingResp"

        const val KEY_STATION = "station"

        /**
         * do not update this value now!!
         */
        const val SEND_TIMES = 1

        const val COL_RTU_DEVICE = "rtuDevice"

        const val COL_RTU_DEVICE_HIST = "rtuDeviceHist"

        const val KEY_FIRM_ID = "firmId"
        const val KEY_RTU_ID = "rtuId"

    }
}